package com.ruoyi.utils;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import java.io.FileInputStream;
import java.io.IOException;

public class WordToTextConverter {

    public static void main(String[] args) {
//        String docFilePath = "/opt/code/document.doc";
        String docxFilePath = "/opt/code/document.docx";

        try {
            // 处理 .doc 文件
//            String docText = extractTextFromDoc(docFilePath);
//            System.out.println("Text from .doc file:");
//            System.out.println(docText);

            // 处理 .docx 文件
            String docxText = extractTextFromDocx(docxFilePath);
            System.out.println("Text from .docx file:");
            System.out.println(docxText);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    // 提取 .doc 文件中的文本
    public static String extractTextFromDoc(String filePath) throws IOException {
        try (FileInputStream fis = new FileInputStream(filePath);
             HWPFDocument document = new HWPFDocument(fis);
             WordExtractor extractor = new WordExtractor(document)) {
            return extractor.getText();
        }
    }

    // 提取 .docx 文件中的文本
    public static String extractTextFromDocx(String filePath) throws IOException {
        try (FileInputStream fis = new FileInputStream(filePath);
             XWPFDocument document = new XWPFDocument(fis);
             XWPFWordExtractor extractor = new XWPFWordExtractor(document)) {
            return extractor.getText();
        }
    }
}
